package com.cucker.urlforwarder.controller;

import com.cucker.urlforwarder.UrlForwarderApplication;
import com.cucker.urlforwarder.config.MyconfigProperties;
import com.cucker.urlforwarder.entity.Record;
import com.cucker.urlforwarder.service.RecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ConcurrentModel;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class HomeController {
    private static final Logger logger = LoggerFactory.getLogger(UrlForwarderApplication.class);

    @Autowired
    private RecordService recordService;
    
    // 当 @RequestMapping(value = {"/**"})
    // 或 @RequestMapping(value = {"**"}) 时，静态资源访问不了
    @RequestMapping(value = { "/{variable:(?!asset).*}/**", "/*"})
    public Object index(@RequestHeader("Host") String host, Model model) {
        // 默认响应页面
        String defaultPage = "index";

        List<Record> records = recordService.getURLForwardRecordByFqdn(host);
        if (records == null || records.size() == 0) {
            return defaultPage;
        }
        Record r = records.get(0);

        switch (r.getBasic()) {
            // 隐性URL
            case 200 -> {
                model.addAttribute("url", r.getData());
                // Thymeleaf模板
                return "forward/200forward";
            }
            // 301 重定向显性URL
            case 301 -> {
                return ResponseEntity.status(301).header(HttpHeaders.LOCATION, r.getData()).build();
            }
            // 302 重定向显性URL
            case 302 -> {
                return ResponseEntity.status(302).header(HttpHeaders.LOCATION, r.getData()).build();
            }
        }

        return defaultPage;
    }
}
